package com.example.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
public class HttpUtil {
    public String sendGetRequest(String url, String params) throws IOException {
        URL requestUrl = new URL(url + "?" + params);
        HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();
        } else {
            throw new IOException("HTTP request failed with status code: " + responseCode);
        }
    }

    public String sendPostRequest(String url, Integer connectTimeout,
            Integer readTimeout, String contentType, Map<String, String> heads,
            Map<String, String> params) throws IOException {
        URL u;
        HttpURLConnection connection = null;
        OutputStream out;
        try {
            u = new URL(url);
            connection = (HttpURLConnection) u.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(readTimeout);
            connection.setRequestProperty("Content-Type", contentType);
            // POST请求必须设置该属性
            connection.setDoOutput(true);
            connection.setDoInput(true);
            if (heads != null) {
                for (Map.Entry<String, String> stringStringEntry : heads.entrySet()) {
                    connection.setRequestProperty(stringStringEntry.getKey(),
                            stringStringEntry.getValue());
                }
            }

            out = connection.getOutputStream();
            if (params != null && !params.isEmpty()) {
                out.write(toJSONString(params).getBytes());
            }
            out.flush();
            out.close();

            // 获取请求返回的数据流
            InputStream is = connection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 封装输入流is，并指定字符集
            int i;
            while ((i = is.read()) != -1) {
                baos.write(i);
            }
            return baos.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String toJSONString(Map<String, String> map) {
        Iterator<Entry<String, String>> i = map.entrySet().iterator();
        if (!i.hasNext()) {
            return "{}";
        }

        StringBuilder sb = new StringBuilder();
        sb.append('{');
        for (;;) {
            Map.Entry<String, String> e = i.next();
            String key = e.getKey();
            String value = e.getValue();
            sb.append("\"");
            sb.append(key);
            sb.append("\"");
            sb.append(':');
            sb.append("\"");
            sb.append(value);
            sb.append("\"");
            if (!i.hasNext()) {
                return sb.append('}').toString();
            }
            sb.append(',').append(' ');
        }
    }
}
